package com.example.ktapplication.fragment

import android.os.Bundle
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.RecyclerView
import com.example.ktapplication.activity.SysBlogListActivity
import com.example.ktapplication.adapter.SystemListAdapter
import com.example.ktapplication.base.BaseTitleRvFragment
import com.example.ktapplication.bean.Sys
import com.example.ktapplication.bean.SysBlogList
import com.example.ktapplication.enum.StateLayoutMode
import com.example.ktapplication.model.SystemViewModel
import com.example.ktapplication.utils.LogHelper
import com.example.ktapplication.utils.toJson

class SystemFragment : BaseTitleRvFragment() {

    companion object {
        private var instance: SystemFragment? = null

        fun getInstance(): SystemFragment {
            if (instance == null) {
                instance = SystemFragment()
            }
            return instance!!
        }
    }

    private val viewModel by lazy {
        ViewModelProvider(this)[SystemViewModel::class.java]
    }

    private val systemListAdapter by lazy {
        SystemListAdapter().apply {
            itemCallBack = object : SystemListAdapter.OnItemClickListener {
                override fun onLinkClick(sys: Sys, sysChild: Sys.SysChild) {
                    val curIndex = sys.children.indexOf(sysChild)
                    jumpSysBlog(curIndex, sys)
                }

                override fun onTitleClick(sys: Sys) {
                    jumpSysBlog(0, sys)
                }
            }
        }

    }

    override fun initAdapter(): RecyclerView.Adapter<RecyclerView.ViewHolder> {
        return systemListAdapter
    }

    override fun getTitleBarStr(): String {
        return "知识体系"
    }

    override fun onDate(savedInstanceState: Bundle?) {
        viewModel.sysData.observe(this) {
            LogHelper.e("---ext ${javaClass.simpleName} sysData >>> ${it.toJson()}")
            systemListAdapter.addData(it)
            loadDataFinish()
        }
        viewModel.addViewModelState {
            if (it != StateLayoutMode.CONTENT) {
                systemListAdapter.addData(mutableListOf())
                loadDataFinish()
            }
        }
    }

    override fun loadData() {
        viewModel.getSys()
    }

    override fun loadMoreData() {
        loadDataFinish()
    }

    private fun jumpSysBlog(curIndex: Int, sys: Sys) {
        SysBlogListActivity.start(requireActivity(), SysBlogList(curIndex, sys))
    }

}
